<template>
  <div class="view-container">

    <div class="main-content">

      <div class="list-container" style="padding-top: 0">

        <search-from :form-list="formList" :indexLength="3" @onConfirm="filterDataConfirm" @onReset="filterReset" />

        <table-view :cell-style="cellStyle" :data="tableData" border header-cell-class-name="table-header" size="small"
          @row-click="aloneClick">

          <el-table-column :min-width="160" :show-overflow-tooltip="true" fixed="left" header-align="center" label="编号"
            prop="terminalNo" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" fixed="left" header-align="center"
            label="终端名称" prop="terminalName" />

          <el-table-column :min-width="180" :show-overflow-tooltip="true" fixed="left" header-align="center"
            label="所在地区">
            <template #default="{row}">
              <span v-if=" row.provinceName">{{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}</span>
            </template>
          </el-table-column>

          <el-table-column :min-width="120" :show-overflow-tooltip="true" align="center" label="终端类型"
            prop="terminalType">
            <template #default="{row}">
              {{ getLabel('app_mode', row.terminalType) }}
            </template>
          </el-table-column>

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="产品通用名">
            <template #default="{row}">
              <span>{{ row.productPopularName }}</span>
            </template>
          </el-table-column>

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="商品名"
            prop="productName" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="包装规格"
            prop="packSpecs" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="生产厂家"
            prop="producer" />

          <el-table-column :min-width="200" :show-overflow-tooltip="true" header-align="center" label="配送商"
            prop="distributeName">
            <template #default="{row}">
              <distributors-view v-if="row.distributeContractDetails && row.distributeContractDetails.length"
                :booleType="false" :datas="row.distributeContractDetails" :unit="row.productInfoDetail?.sellUnit" />
            </template>
          </el-table-column>
<!-- 
          <el-table-column :min-width="180" :show-overflow-tooltip="true" align="center" label="开发期限截至">
            <template #default="{row}">
              {{ dateFormat("yyyy-mm-dd", row.expireTime) }}
            </template>
          </el-table-column>

          <el-table-column :min-width="180" :show-overflow-tooltip="true" align="center" label="注册日期">
            <template #default="{row}">
              {{ dateFormat("yyyy-mm-dd", row.agentRegisterTime) }}
            </template>
          </el-table-column> -->

          <el-table-column :min-width="180" :show-overflow-tooltip="true" align="center" label="负责营销职员"
            prop="headName" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" align="center" fixed="right" label="状态">
            <template #default="{row}">
              <div v-if="row.flowStatus !=='DOING'" style="line-height: 20px;">
                {{ getLabel('fine_terminal', row.devStatus) }}
              </div>
              <div v-if="row.flowStatus ==='DOING'" style="line-height: 20px;">
                {{ getLabel('approval_result', row.flowStatus) }}
              </div>
              <div class="flow-status-color" style="line-height: 20px; ">
                {{ distributeStatus(row.distributeContractDetails) }}
              </div>
            </template>
          </el-table-column>

          <el-table-column :min-width="270" align="center" fixed="right" label="操作">
            <template #default="{row}">

              <el-button v-auth="{v:['crm:marketing:matching:direct:set'],
                   bool:row?.devStatus === '2' || row?.devStatus === '4' || row?.devStatus === '5'}" type="text"
                @click="handlSet(row)">
                设置配送信息
              </el-button>

              <el-button v-auth="{v:['crm:marketing:matching:direct:termination'],bool:row?.devStatus === '5'}"
                type="text" @click="handlTermination(row.id,1)">
                终止交易
              </el-button>

              <el-button v-auth="{v:['crm:marketing:matching:direct:failure'],bool:row?.devStatus === '4' || row?.devStatus === '2'}" type="text"
                @click="handlFailure(row,1)">
                开发失败
              </el-button>
            </template>

          </el-table-column>
        </table-view>

        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.page" :total="total"
          style="display: flex; justify-content: flex-end" @pagination="handlList" />

      </div>

    </div>

    <!--设置配送信息-->
    <setiDelivery ref="setiDeliveryDialog" @distributeSuccsess="distributeSuccsess" />

    <!-- 开发中产品详情 -->
    <detail-drawer ref="detailDrawer" :size-width="1000" custom-title>
      <template #title>
        <div style="display: flex;justify-content: space-between;align-items: center">
          <div style="width: 70%">
            <span style="padding-right: 15px">{{ rowData?.terminalName }} </span>
            <el-tag v-if="rowData?.flowStatus!=='DOING'" size="small" type="warning">
              {{ getLabel('fine_terminal', rowData?.devStatus) }}
            </el-tag>
          </div>
          <div v-if="rowData" style="width: 30%;text-align: right">

            <el-button v-auth="{v:['crm:marketing:matching:direct:set'],
              bool:rowData?.devStatus === '2' || rowData?.devStatus === '4' || rowData?.devStatus === '5'}" size="mini"
              type="primary" @click="handlSet(rowData)">
              设置配送信息
            </el-button>

            <el-button v-auth="{v:['crm:marketing:matching:direct:termination'],bool:rowData?.devStatus === '5'}"
              size="mini" type="primary" @click="handlTermination(rowData?.id,2)">
              终止交易
            </el-button>

            <el-button v-auth="{v:['crm:marketing:matching:direct:failure'],bool:rowData?.devStatus === '4' || rowData?.devStatus === '2'}"
              size="mini" type="primary" @click="handlFailure(rowData,2)">
              开发失败
            </el-button>
          </div>
        </div>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <direct-details ref="productDetailDrawer" :product-id="rowData?.id" />
          </div>
        </div>
      </template>
    </detail-drawer>

  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRoute } from "vue-router";
import { crmStore } from "@CRM/store";
import area from "@/utils/area";

export default {
  name: "index",
  components: {
    setiDelivery: defineAsyncComponent(() =>
      import("@CRM/views/marketing/customer/terminal/modules/setiDelivery.vue")
    ),
    directDetails: defineAsyncComponent(() =>
      import("@CRM/views/commonView/marketing/matching/directDetails.vue")
    ),
    productBaseInfo: defineAsyncComponent(() =>
      import(
        "@CRM/views/commonView/detailComponents/product/productBaseInfo.vue"
      )
    ),
  },
  setup() {
    const api = inject("api");
    const route = useRoute();
    const currentInstance = getCurrentInstance();
    const handleArray = (str) => {
      let arr = crmStore.getters["dictionary/getDictionary"][str] || [];
      return arr;
    };
    const data = reactive({
      tableData: [],
      queryParams: {
        pageSize: 20,
        page: 1,
        terminalId: "", //终端Id
        terminalName: "", // 终端名称
        productId: "", //产品id、
        productName: "", //产品
        devStatus: "", //状态
        headId: "", // 职员id
        registerStartTime: null, // 注册日期开始
        registerEndTime: null, //  注册日期结束
        expireTimeStartTime: null, // 开发截止日期开始时间
        expireTimeEndTime: null, // 开发截止日期结束时间
        provinceCode: "", //终端省Code
        cityCode: "", //终端市Code
        areaCode: "", //终端区Code
        terminalListType: "2",
        listType: "2",
      },
      total: 0,
      formList: [
        {
          key: "devStatus",
          label: "状态",
          form_type: "select",
          value: "",
          is_search: false,
          options: handleArray("fine_terminal").filter(
            (a) =>
              a.value !== "1" &&
              a.value !== "-1" &&
              a.value !== "0" &&
              a.value !== "-6" &&
              a.value !== "-7" &&
              a.value !== "-8"
          ),
        },
        {
          key: "terminalName",
          label: "终端名称",
          form_type: "text",
          value: "",
          is_search: false,
          options: [],
        },
        {
          key: "productId",
          label: "产品名称",
          form_type: "select_product",
          value: "",
          is_search: false,
          options: [],
          setting: {
            label: "productName",
            value: "productId",
          },
        },
        {
          key: "headId",
          label: "负责销售职员",
          form_type: "select",
          value: "",
          is_search: false,
          options: crmStore.getters["company/getHeadOptions"] || [],
          setting: {
            label: "realName",
            value: "id",
          },
        },
        {
          key: "area",
          label: "所在地区",
          form_type: "cascader",
          value: [],
          is_search: false,
          multiple: false,
          checkStrictly: false,
          options: area,
        },
        {
          key: "date_range1",
          label: "注册日期",
          form_type: "daterange",
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: "date_range2",
          label: "开发期限截至",
          form_type: "daterange",
          value: [],
          is_search: false,
          options: [],
        },
      ],
      setiDeliveryDialog: null,
      detailDrawer: null,
      rowData: null,
    });

    // 获取产品下拉
    const handlProductData = async () => {
      const res = await api.terminal.TERMINAL_PRODUCTID({ terminalId: 0 });
      if (res.code === 0) {
        data.formList[2].options = res.data;
      }
    };

    //获取列表
    const handlList = () => {
      api.terminal.PRODUCT_LIST(data.queryParams).then((res) => {
        if (res.code === 0) {
          data.tableData = res.data.list || [];
          data.total = res.data.total;
        }
      });
    };

    // 获取配送信息审核中
    const distributeStatus = (val) => {
      let a = "";
      if (val && val.length > 0) {
        for (let i = 0; i < val.length; i++) {
          if (val[i].flowStatus === "DOING") {
            a = "配送信息审核中";
            break;
          }
        }
      }
      return a;
    };

    // 确定搜所
    const filterDataConfirm = (val) => {
      data.queryParams.devStatus = val.devStatus;
      data.queryParams.terminalName = val.terminalName;
      data.queryParams.productId = val.productId;
      data.queryParams.provinceCode = val.area[0];
      data.queryParams.cityCode = val.area[1];
      data.queryParams.areaCode = val.area[2];
      data.queryParams.headId = val.headId;
      data.queryParams.registerStartTime = val.date_range1[0];
      data.queryParams.registerEndTime = val.date_range1[1];
      data.queryParams.expireTimeStartTime = val.date_range2[0];
      data.queryParams.expireTimeEndTime = val.date_range2[1];
      data.queryParams.page = 1;
      handlList();
    };

    // 取消
    const filterReset = () => {
      data.queryParams = {
        pageSize: 20,
        page: 1,
        terminalId: "", //终端Id
        terminalName: "", // 终端名称
        productId: "", //产品id、
        productName: "", //产品
        devStatus: "", //状态
        headId: "", // 职员id
        registerStartTime: null, // 注册日期开始
        registerEndTime: null, //  注册日期结束
        expireTimeStartTime: null, // 开发截止日期开始时间
        expireTimeEndTime: null, // 开发截止日期结束时间
        provinceCode: "", //终端省Code
        cityCode: "", //终端市Code
        areaCode: "", //终端区Code
        terminalListType: "2",
        listType: "2",
      };
      handlList();
    };

    // 设置配送信息
    const handlSet = (val) => {
      data.setiDeliveryDialog.open(val, val.id);
    };

    //终止交易
    const handlTermination = (id, num) => {
      currentInstance.proxy
        .alertBox({
          message: "终止交易后不可撤销操作，确定终止该终端此产品交易关系？",
        })
        .then(() => {
          api.terminal.TRADINGPRODUCT_TERMINATION(id).then((res) => {
            if (res.code === 0) {
              if (num === 1) {
                handlList();
              } else {
                data.fineDetailsDrawer.handlDetails(id);
              }
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    //开发失败
    const handlFailure = (row, num) => {
      currentInstance.proxy
        .alertBox({
          message: "确认更改该终端产品状态为开发失败？",
        })
        .then(() => {
          api.terminal.TERMINAL_FAILURE(row.id).then((res) => {
            if (res.code === 0) {
              if (num === 1) {
                handlList();
              } else {
                data.fineDetailsDrawer.handlDetails(row.id);
              }
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    //设置配送信息成功回调
    const distributeSuccsess = () => {
      handlList();
    };

    const aloneClick = (row, column, event) => {
      data.rowData = row;
      if (column.label === "操作") {
        return;
      }
      data.detailDrawer.open();
    };

    const cellStyle = () => {
      return "cursor:pointer;";
    };

    onMounted(() => {
      handlList();
      handlProductData();
    });

    return {
      ...toRefs(data),
      handlProductData,
      handlList,
      filterDataConfirm,
      filterReset,
      handlSet,
      distributeSuccsess,
      aloneClick,
      cellStyle,
      distributeStatus,
      handlTermination,
      handlFailure,
    };
  },
};
</script>

<style scoped>
/* @import url(); 引入css类 */
</style>
